package com.gemini.web.servlet;

import com.gemini.pojo.User;
import com.gemini.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    UserServiceImpl userService=new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");
        User user=userService.selectUser(new User(null,username,password));
        if(user!=null){
            if(remember==null){
                Cookie[] cookies = request.getCookies();
                for(Cookie cookie:cookies){
                    if(cookie.getName().equals("username") || cookie.getName().equals("password")){
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    }
                }
            }else {
                Cookie usernameCookie = new Cookie("username", username);
                Cookie passwordCookie = new Cookie("password", password);
                usernameCookie.setMaxAge(60*10);
                passwordCookie.setMaxAge(60*10);
                response.addCookie(usernameCookie);
                response.addCookie(passwordCookie);
            }
            HttpSession session = request.getSession();
            session.setAttribute("username",username);
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath+"/selectAll");
        }else {
            request.setAttribute("login_msg","用户名或密码错误");
            Cookie[] cookies = request.getCookies();
            for(Cookie cookie:cookies){
                if(cookie.getName().equals("username") || cookie.getName().equals("password")){
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                }
            }
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        this.doGet(request, response);
    }
}
